<template>
    <van-nav-bar v-if="isJoin != 1" title="发起拼团" left-text="" left-arrow @click-left="goBack" />
    <van-nav-bar v-else title="参与拼团" left-text="" left-arrow @click-left="goBack" />

    <!-- 地址 -->
    <van-contact-card v-if="Object.values(Address).length > 0" type="edit" :tel="Address.mobile"
        :name="Address.consignee" @click="toAddressPage" />
    <van-contact-card v-else type="add" @click="toAddressPage" />

    <!-- 商品信息 -->
    <van-card :price="prices" :title="product.name" class="goods-card" :thumb="product.thumbs_text"
        @click-thumb="toPageInfo(proid)" :num="nums">
        <template #desc>
            <div v-if="attrs">
                <van-tag v-for="items in attrs" type="warning" size="medium" style="margin-right: 10px;">{{items.name }}</van-tag>
            </div>
            <div>单价： {{ product.buy }}</div>
        </template>
    </van-card>

    <!--支付方式 -->
    <van-field v-model="payName" is-link readonly label="支付方式" placeholder="选择支付方式" @click="showPayPicker = true" />
    <van-popup v-model:show="showPayPicker" destroy-on-close position="bottom">
        <van-picker :columns="columnsPay" @confirm="onPayConfirm" @cancel="showPayPicker = false" />
    </van-popup>

    <!-- 订单备注 -->
    <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
        show-word-limit />

    <!-- 提交订单 -->
    <van-submit-bar v-if="isJoin != 1" :price="total" button-text="确认支付" @submit="onSubmit" />
    <van-submit-bar v-else :price="total" button-text="确认支付" @submit="onSubmitJoin" />
</template>

<script setup>
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ?? {})
const Address = ref(proxy.$cookies.get('Address') ? proxy.$cookies.get('Address') : {})
const proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
const nums = proxy.$route.query.nums ? proxy.$route.query.nums : 0
const isJoin = proxy.$route.query.isJoin ? proxy.$route.query.isJoin : 0
const attrs = ref(proxy.$cookies.get('relationids') ? JSON.parse(proxy.$cookies.get('relationids')) : [])
const product = ref({})
const prices = ref(0)
const remark = ref('')

// 支付方式 
const showPayPicker = ref(false)
const payName = ref('')
const pay = ref('')
const columnsPay = [
    { text: '余额支付', value: 'money' },
    { text: '支付宝', value: 'zfb' },
    { text: '微信支付', value: 'wx' },
]

onBeforeMount(() => {
    if (Object.values(Address.value).length <= 0) {
        getAddressData()
    }
    getProductInfoData()
})

const getAddressData = async () => {
    let result = await Api.AddressOrder({
        busid: LoginUser.id,
    })

    if (result.code == 1) {
        let data = result.data
        Address.value = {
            id: data.id,
            consignee: data.consignee,
            mobile: data.mobile
        }
    }
}

const toAddressPage = () => {
    proxy.$router.push({
        path: '/address/index',
        query: {
            action: 'order'
        }
    })
}

const getProductInfoData = async () => {
    let result = await Api.ProductInfo({
        proid: proid,
        busid: LoginUser.id ?? 0
    })
    if (result.code == 1) {
        product.value = result.data.info
    }
}

const onPayConfirm = ({ selectedValues, selectedOptions }) => {
    payName.value = selectedOptions[0]?.text;
    pay.value = selectedOptions[0]?.value;
    showPayPicker.value = false;
};

const total = computed(() => {
    let num = 0;
    if(attrs.value.length > 0)
    {
        let totals = attrs.value.reduce((accumulator, item) => accumulator + (parseFloat(item.price) / 100), 0,);
        prices.value = parseFloat(product.value.buy) + parseFloat(totals)
        num = (parseFloat(prices.value) * parseInt(nums)).toFixed(2);
    }   
    else
    {
        num = (parseFloat(product.value.buy) * parseInt(nums)).toFixed(2);
        prices.value = parseFloat(product.value.buy)
    }

    return num * 100
})

const onSubmit = async () => {
    if (!payName.value) {
        error('请选择支付方式');
        return false;
    }

    if (JSON.stringify(Address.value) == '{}') {
        error('请选择收货地址');
        return false;
    }

    let data = {
        busid: LoginUser.id,
        total: total.value / 100,
        proid: proid,
        addrid: Address.value.id,
        nums: nums,
        pay: pay.value,
        remark: remark.value,
    }

    let relationids = []

    // 判断是否有属性
    if(attrs.value.length > 0)
    {
        attrs.value.forEach((item) => {
            relationids.push(item.id)  
        })

        data.attrs = relationids.toString()
    }

    let result = await Api.TeamAdd(data);
    if (result.code == 1) {
        success({
            message: result.msg,
            onClose: () => {
                proxy.$router.push('/team/index')
            }
        });

    } else {
        error(result.msg);
    }
}

const onSubmitJoin = async () => {
    if (!payName.value) {
        error('请选择支付方式');
        return false;
    }

    if (JSON.stringify(Address.value) == '{}') {
        error('请选择收货地址');
        return false;
    }

    let data = {
        busid: LoginUser.id,
        total: total.value / 100,
        proid: proid,
        addrid: Address.value.id,
        nums: nums,
        pay: pay.value,
        remark: remark.value,
    }

    let relationids = []

    // 判断是否有属性
    if(attrs.value.length > 0)
    {
        attrs.value.forEach((item) => {
            relationids.push(item.id)  
        })

        data.attrs = relationids.toString()
    }

    let result = await Api.TeamJoin(data);
    if (result.code == 1) {
        success({
            message: result.msg,
            onClose: () => {
                proxy.$router.push('/team/index')
            }
        });

    } else {
        error(result.msg);
    }
}
</script>
